package com.alimama.aop;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alimama.commoms.SysContent;

@Aspect
@Component("logAspect")
public class LogAspect {

	private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);

	@Pointcut("@annotation(com.alimama.aop.BusAnnotion)")
	private void deal() {}

	/**
	 * @Description: 方法调用前触发
	 * @param joinPoint
	 */
	@Around("deal()")
	public Object before(ProceedingJoinPoint joinPoint) {

		// 先执行业务
		Object obj = "";
		
		// 获取request,response，session
		HttpServletRequest request = SysContent.getRequest();
		HttpServletResponse response = SysContent.getResponse();
		HttpSession session = request.getSession();
		
		logger.info("request--->"+request);
		logger.info("response--->"+response);
		logger.info("session--->"+session);

		// 获取拦截的方法名
		Signature signature = joinPoint.getSignature();
		MethodSignature methodSignature = (MethodSignature) signature;

		// 获取自定义注解的参数（相当于new了一个BusAnnotion对象）
		BusAnnotion busAnnotion = methodSignature.getMethod().getAnnotation(BusAnnotion.class);

		try {// 先执行业务
			obj = joinPoint.proceed();
		} catch (Throwable e) {
			logger.error(e.getMessage());
		}

		/**
		 * 处理日志
		 */
		try {
			// 获取方法的参数名称
			String[] parameterNames = methodSignature.getParameterNames();
			for (int i = 0; i < parameterNames.length; i++) {
				logger.info("parameterNames--->" + parameterNames[i]);
			}
			// 获取方法的参数值
			Object[] args = joinPoint.getArgs();
			for (int k = 0; k < args.length; k++) {
				Object arg = args[k];
				logger.info("args:" + arg);
				// 获取参数类型
				String typeName = arg.getClass().getTypeName();
				logger.info("typeName:" + typeName);
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}

		return obj;
		// 记录日志到数据库
	}
}
